﻿using Enter.Utils.EnumExt;
using System;
using System.Linq;

namespace Enter.Excel
{
    public class ToolExtend
    {
        public static string ToString(object obj, string format, bool isDrop = false)
        {
            if (obj == null) return string.Empty;
            var t = obj.GetType();
            var o_val = string.Empty;

            if (t.IsEnum)
            {
                o_val = Convert.ToString(obj);
                if (o_val == "0")
                {
                    // 处理枚举不是从0开始;
                    o_val = string.Empty;
                }
            }
            else if (isDrop)
            {
                o_val = Convert.ToString(obj);
                var item = EnumExtend.EnumList(format).Where(t => t.Value == o_val).FirstOrDefault();
                if (item == null)
                {
                    o_val = string.Empty;
                }
                else
                {
                    o_val = item.Text;
                }
            }
            else
            {
                switch (Type.GetTypeCode(t))
                {
                    case TypeCode.DateTime:

                        if (string.IsNullOrWhiteSpace(format))
                        {
                            format = "yyyy-MM-dd";// HH:mm:ss
                        }
                        // 转换
                        {
                            DateTime data = (DateTime)obj;
                            if (data == DateTime.MinValue) o_val = string.Empty;
                            else o_val = data.ToString(format);
                        }
                        break;
                    case TypeCode.Boolean:
                        if (string.IsNullOrWhiteSpace(format))
                        {
                            format = "是:否";
                        }
                        var tfs = format.Split(":");
                        // 转换
                        {
                            bool data = (bool)obj;
                            if (data)
                            {
                                o_val = tfs[0];
                            }
                            else
                            {
                                o_val = tfs[1];
                            }
                        }
                        break;
                    default:
                        o_val = Convert.ToString(obj);
                        break;
                }
            }
            return o_val;
        }
    }
}
